package com.caiyi.financial.nirvana.sms.scheduled;

import com.caiyi.financial.nirvana.sms.gateway.Controller;
import com.caiyi.financial.nirvana.sms.gateway.DefaultGateWay;
import com.caiyi.financial.nirvana.sms.gateway.GateWayThread;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class QueryReceiveMsgTask {

    private static final Logger logger = LoggerFactory.getLogger(QueryReceiveMsgTask.class);

    /**
     * 每2分钟执行一次
     * 定时获取上行信息
     */
    @Scheduled(fixedRate = Constant.TEN_MINUTES_OF_SECOND * 1000 / 5, initialDelay = Constant.TEN_MINUTES_OF_SECOND * 1000 / 5)
    public void queryReceiveMsg() {
        String lockKey = String.format(JedisKey.SMS_SCHEDULED_KEY_METHOD, "queryReceiveMsgSchedule ", "queryReceiveMsg");
        boolean checkStatus = CommUtil.checkStatus(lockKey, Constant.TEN_MINUTES_OF_SECOND / 20);
        if (checkStatus) {
            Collection<GateWayThread<? extends DefaultGateWay>> gateWayThreads = Controller.getCurrentGateWay().values();
            for (GateWayThread gateWayThread : gateWayThreads) {
                DefaultGateWay defaultGateWay = gateWayThread.getGateWay();
                try {
                    boolean status = defaultGateWay.queryReceiveMsg();
                    logger.info("QueryReceiveMsg ：{} 获取上行信息是否成功：{}", defaultGateWay.info.getName(), status);
                } catch (NoSuchMethodException e1) {
                    logger.info("QueryReceiveMsg: {} 未实现获取上行信息方法", defaultGateWay.info.getName());
                } catch (Exception e) {
                    logger.error("QueryReceiveMsg Error !", e);
                }
            }
        }
    }

}
